package me.fung.rem.app.auth

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import me.fung.keen.app.view.Presenter
import me.fung.keen.component.message.msg
import me.fung.rem.app.GlobalState
import me.fung.rem.bean.repo.configAutoSignUp
import me.fung.rem.bean.repo.configCacheInput
import me.fung.rem.bean.repo.configPassword

/**
 * 注册和修改密码界面
 */
class SignUpPresenter : Presenter() {

    var deprecatedPwd by mutableStateOf("")
    var pwd by mutableStateOf("")
    var repeatPwd by mutableStateOf("")

    fun signUp() {
        if (setPwd()) {
            GlobalState.hasKey = true
        }
    }

    private fun setPwd(): Boolean {
        if (pwd == "") {
            msg.send { info("密码不能为空") }
            return false
        }
        if (pwd != repeatPwd) {
            msg.send { info("再次密码不一致") }
            return false
        }
        val encryptor = GlobalState.passwordEncryptor()
        configPassword = encryptor.encryptPassword(pwd)
        configCacheInput = ""
        configAutoSignUp = false
        return true
    }

    fun modifyPwd() {
        if (deprecatedPwd == "") {
            msg.send { info("旧密码不能为空") }
            return
        }

        if (!GlobalState.passwordEncryptor().checkPassword(deprecatedPwd, configPassword)) {
            msg.send { info("旧密码不正确") }
            return
        }
        if (setPwd()) {
            GlobalState.hasKey = true
            GlobalState.authorized = false
        }
    }
}